package com.smartfast4j.backend.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.smartfast4j.backend.common.bean.R;
import com.smartfast4j.backend.common.controller.WebBaseController;
import com.smartfast4j.backend.common.util.CacheUtil;
import com.smartfast4j.backend.common.util.RSAUtils;
import com.smartfast4j.backend.common.util.ShiroUtils;
import com.smartfast4j.backend.modules.sys.security.shiro.SysUserRealm;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * Created by gacl on 2017/3/3.
 */
@Controller
public class SysLoginController extends WebBaseController {

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserRealm userRealm;

    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        logger.debug("图片验证码="+text);
        //将验证码保存到缓存中
        CacheUtil.setString(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login")
    public R login(String username, String password, String captcha)throws IOException {
        //从缓存中取出验证码
        String kaptcha = CacheUtil.getString(Constants.KAPTCHA_SESSION_KEY);
        //校验验证码
        if(StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(kaptcha)){
            //清除缓存中的验证码
            CacheUtil.delete(Constants.KAPTCHA_SESSION_KEY);
            return R.error("验证码不正确");
        }
        try{
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            //password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //将登录逻辑交由shiro处理
            subject.login(token);
            //获取当前会话的唯一标识作为登录token返回给客户端。
            String loginToken = subject.getSession().getId().toString();
            logger.info("loginToken="+loginToken);
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("token",loginToken);
            return R.okEncrypt(dataMap);
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        }catch (LockedAccountException e) {
            return R.error(e.getMessage());
        }catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/sys/logout")
    @ResponseBody
    public R logout() {
        //注销
        ShiroUtils.logout();
        return R.ok();
    }
}
